import { ref, computed } from 'vue';
import { showToast } from 'vant';
import { 
  getAppointmentList, 
  cancelAppointment, 
  rateAppointment,
  getAvailableTimeSlots
} from '../services/appointment.service';

/**
 * 预约列表相关逻辑
 */
export function useAppointmentList() {
  const loading = ref(false);
  const refreshing = ref(false);
  const finished = ref(false);
  const appointments = ref<Appointment[]>([]);
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  
  // 加载预约列表
  const loadAppointments = async (status: string = '') => {
    if (refreshing.value) {
      appointments.value = [];
      currentPage.value = 1;
      finished.value = false;
    }
    
    try {
      loading.value = true;
      const params = {
        page: currentPage.value,
        pageSize: pageSize.value,
        status
      };
      
      const res = await getAppointmentList(params);
      
      if (refreshing.value) {
        appointments.value = [];
        refreshing.value = false;
      }
      
      if (res.data) {
        appointments.value = [...appointments.value, ...res.data.list];
        total.value = res.data.total;
        
        // 判断是否已加载完全部数据
        if (appointments.value.length >= total.value) {
          finished.value = true;
        }
        
        currentPage.value++;
      }
    } catch (error) {
      console.error('加载预约列表失败', error);
    } finally {
      loading.value = false;
    }
  };
  
  // 刷新列表
  const onRefresh = () => {
    refreshing.value = true;
    finished.value = false;
    currentPage.value = 1;
    loadAppointments();
  };
  
  // 过滤预约
  const filterAppointments = (status: string) => {
    if (status === 'all') {
      return appointments.value;
    }
    return appointments.value.filter(item => item.status === status);
  };
  
  return {
    loading,
    refreshing,
    finished,
    appointments,
    loadAppointments,
    onRefresh,
    filterAppointments
  };
}

/**
 * 预约取消相关逻辑
 */
export function useAppointmentCancel() {
  const cancelLoading = ref(false);
  const currentAppointmentId = ref<number>();
  
  // 取消预约
  const cancelAppointmentAction = async (id: number, reason: string) => {
    try {
      cancelLoading.value = true;
      currentAppointmentId.value = id;
      
      const res = await cancelAppointment(id, reason);
      
      if (res.code === 0 || res.code === 200) {
        showToast('预约已取消');
        return true;
      }
      return false;
    } catch (error) {
      console.error('取消预约失败', error);
      return false;
    } finally {
      cancelLoading.value = false;
      currentAppointmentId.value = undefined;
    }
  };
  
  return {
    cancelLoading,
    currentAppointmentId,
    cancelAppointmentAction
  };
}

/**
 * 预约时间段选择相关逻辑
 */
export function useTimeSlotSelection(doctorId: number) {
  const loading = ref(false);
  const scheduleDates = ref<{day: string; date: string; available: boolean; rawDate?: string}[]>([]);
  const timeSlots = ref<{time: string; available: boolean; remaining: number; fee: number}[]>([]);
  const activeDate = ref(0);
  const selectedTimeSlot = ref<number>();
  
  // 生成未来7天的日期数据
  const generateScheduleDates = () => {
    const dates: {day: string; date: string; available: boolean; rawDate?: string}[] = [];
    const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const today = new Date();
    
    for (let i = 0; i < 7; i++) {
      const date = new Date();
      date.setDate(today.getDate() + i);
      
      let day;
      if (i === 0) {
        day = '今天';
      } else if (i === 1) {
        day = '明天';
      } else {
        day = dayNames[date.getDay()];
      }
      
      const month = date.getMonth() + 1;
      const dayOfMonth = date.getDate();
      
      dates.push({
        day,
        date: `${month}/${dayOfMonth}`,
        available: true, // 默认可预约，后续会根据医生实际出诊情况更新
        rawDate: `${date.getFullYear()}-${month.toString().padStart(2, '0')}-${dayOfMonth.toString().padStart(2, '0')}` // 用于请求API
      });
    }
    
    scheduleDates.value = dates;
  };
  
  // 加载某天的可用时间段
  const loadTimeSlots = async (index: number = activeDate.value) => {
    if (!doctorId || !scheduleDates.value[index]) return;
    
    try {
      loading.value = true;
      const date = scheduleDates.value[index].rawDate;
      if (!date) return;
      
      const res = await getAvailableTimeSlots(doctorId, date);
      
      if (res.data) {
        timeSlots.value = res.data;
        // 自动清除之前选择的时间段
        selectedTimeSlot.value = undefined;
      }
    } catch (error) {
      console.error('加载可用时间段失败', error);
    } finally {
      loading.value = false;
    }
  };
  
  // 当选择的日期变化时，加载对应的时间段
  const onDateChange = (index: number) => {
    activeDate.value = index;
    loadTimeSlots(index);
  };
  
  // 选择时间段
  const selectTimeSlot = (index: number) => {
    if (timeSlots.value[index]?.available) {
      selectedTimeSlot.value = index;
    }
  };
  
  // 获取选中的日期和时间
  const selectedDateTime = computed(() => {
    if (selectedTimeSlot.value === undefined || !scheduleDates.value[activeDate.value]) return null;
    
    const date = scheduleDates.value[activeDate.value];
    const slot = timeSlots.value[selectedTimeSlot.value];
    
    return {
      date: date.rawDate,
      time: slot.time,
      fee: slot.fee
    };
  });
  
  // 初始化
  generateScheduleDates();
  
  return {
    loading,
    scheduleDates,
    timeSlots,
    activeDate,
    selectedTimeSlot,
    selectedDateTime,
    loadTimeSlots,
    onDateChange,
    selectTimeSlot
  };
} 